#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>



int drv_fd;
int lfd;

int value;


//设备驱动初始化
void driver_init()
{
	drv_fd = open("/dev/led_0", O_RDWR);
	if(drv_fd < 0)
	{
		perror("open");
		exit(1);
	}
}

//socket初始化
void socket_init(const char* argv[])
{	
	//1.创建监听的套接字
    lfd = socket(AF_INET, SOCK_STREAM, 0);
    if (lfd == -1)
    {
        perror("socket error\n");
        exit(1);
    }
	
    //2.lfd和本地的IP和port绑定
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;	//地址族协议  ipv4
    server.sin_port = htons(atoi(argv[2])); //端口号
    inet_pton(AF_INET, argv[1], &server.sin_addr.s_addr);//ip地址
    int ret = bind(lfd, (struct sockaddr*)&server, sizeof(server));
    if (ret == -1)
    {
        perror("bind error\n");
        exit(1);
    }
    
    
    //3.设置监听
    ret = listen(lfd, 20);
    if (ret == -1)
    {
     	perror("listen error\n");
   	    exit(1);
    }

}


int main (int argc, const char* argv[])
{

	if(argc != 3)
	{
		printf("usage:%s serverip port.\n", argv[0]);
		return -1;
	}

	socket_init(argv);

	driver_init();

    //通信
    struct sockaddr_in client;
    socklen_t len = sizeof(client);
	int cfd = accept(lfd, (struct sockaddr*)&client, &len);
    if (cfd == -1)
    {
		perror("accept error");
		exit(1);
    }

	//获取客户端数据
	printf("accept successful\n");
	char ipbuf[64] = {0};
	inet_ntop(AF_INET, &client.sin_addr.s_addr, ipbuf, sizeof(ipbuf)); //获取客户端ip
	printf("client IP:%s, port:%d\n", ipbuf, ntohs(client.sin_port));

	//接收数据
    while(1)
    {
        int len = read(cfd, &value, sizeof(value));
        if(len == -1) //出错
        {
            perror("read error\n");
            exit(1);
        }
        else if (len == 0) //客户端退出 
        {
            close(cfd);
            break;
        }
        else
        {
          	//调用驱动模块
			write(drv_fd, &value, 4);
        }
     
    }

    close(lfd);
	close(cfd);
	close(drv_fd);

    return 0;
	
}
